package com.kid.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.kid.springcloud.entity.Member;
import com.kid.springcloud.entity.Result;
import com.kid.springcloud.handler.CustomGlobalBlockHandler;
import com.kid.springcloud.handler.CustomGlobalFallBackHandler;
import com.kid.springcloud.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class MemberController {

    @Resource
    private MemberService memberService;
    private int num=0;


    @PostMapping("/member/save")
    public Result addMember(@RequestBody Member member) {
        int affected = memberService.addMember(member);
        if (affected > 0) {
            return Result.success("添加会员成功--10004", affected);
        } else {
            return Result.error("401", "添加会员失败");
        }
    }


    //    @GetMapping(value = "/member/get",params = "id")
//    public Result queryById(Long id) {
    @GetMapping("/member/get/{id}")
    public Result queryById(@PathVariable("id") Long id) {

        //模拟超时
//        try {
//            TimeUnit.MILLISECONDS.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Member member = memberService.getMemberById(id);
        if (member != null) {
            return Result.success("查询成功--10004", member);
        } else {
            return Result.error("404", "id=" + id + "查找失败");
        }
    }


    @GetMapping("/t1")
    public Result t1() {
        return Result.success("t1()执行...");
    }

    @GetMapping("/t2")
    public Result t2() throws InterruptedException {
//        线程休眠1s
        TimeUnit.MILLISECONDS.sleep(1000);
        log.info("执行t2()线程id={}", Thread.currentThread().getId());
        return Result.success("t2()执行...");
    }

    @GetMapping("/t6")
    @SentinelResource(value = "t6",blockHandlerClass = CustomGlobalBlockHandler.class,blockHandler = "handlerMethod1",
    fallbackClass = CustomGlobalFallBackHandler.class,fallback = "fallbackMethod1",exceptionsToIgnore = {NullPointerException.class})
    public Result t6(){
        if(++num %5==0){
            throw new NullPointerException("NullPointer异常 num="+num);
        }
        if(num %6==0){
            throw new RuntimeException("Runtime异常 num="+num);
        }
        log.info("执行t6() 线程id={}", Thread.currentThread().getId());
        return Result.success("200","t6()执行成功");
    }
}
